import 'dart:convert';

import 'package:bot_toast/bot_toast.dart';
import 'package:exams_app/gen_a/A.dart';
import 'package:exams_app/home_module/myprofile_module/myprofile_logic.dart';
import 'package:exams_app/net/Address.dart';
import 'package:exams_app/net/DioManager.dart';
import 'package:exams_app/net/persisten_storage.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:get/get.dart';

class MessageModuleLogic extends GetxController {
  int page = 0;

  Rx<MessageModel> messageModel;

  EasyRefreshController esController = EasyRefreshController();

  var dataList = List();


  /// 空数据

  emptyData(){
    if(dataList.length == 0){
      return Container(
        // width: double.infinity,
        // height: double.infinity,
        child: Center(
          child: SizedBox(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Container(

                    child: Column(
                      children: [
                        Image.asset(A.assets_nodata_icon,width: 100,height: 100,),
                        Text('暂无数据',style: TextStyle(fontSize: 13,fontWeight: FontWeight.w600),),
                      ],
                    )
                ),
              ],
            ),
          ),
        ),
      );
    }else{
      return null;
    }
  }

  /// 下拉刷新

  Future<void> onRefresh()async{
    page = 0;
    requestDataWithCollection(true,page: page);
  }
  ///  上拉加载更多
  Future<void> onLoad()async{
    page++;
    requestDataWithCollection(false,page: page);
    await Future.delayed(Duration(milliseconds: 250), () {

    });
  }

  /// 我的资料
  void requestDataWithCollection(bool isHeader,{int page = 0})async{


    var  params = {
      'page':page,
      'limit':'10',
      // 'domain':'${await PersistentStorage().getStorage('uid')}'
      // 'domain': "[('user_id', 'in', ${await PersistentStorage().getStorage('uid')})]",

    };

    String result = await DioUtils(url: await PersistentStorage().getStorage('urlStr')).
    postModel(Address.getattt,function_name:'_api_page',model:'exam.message',params:params );
    Map json = jsonDecode(result);

    messageModel = MessageModel.fromJson(json).obs;


    if(page == 0){

      esController.resetLoadState();
      dataList.clear();
      dataList.addAll(messageModel.value.data);
    }else{

      if(json['data'].length>0){
        // for(int i = 0;i<model.data.length;i++){
        //   model.data[i].isSelect = false;
        // }

        dataList.addAll(messageModel.value.data);
      }else if(json['data'].length <= 0||json['data']==null){
        // _esController.finishLoad(success: true,noMore: true);
        esController.finishLoad(success: true, noMore: true);
        BotToast.showText(text: '暂无更多');
      }
    }

    update();

  }

  @override
  void onInit() {
    // requestDataWithCollection(true,page: 0);
    // TODO: implement onInit
    super.onInit();
  }

}

class MessageModel {
  String search;
  List<Data> data;
  int searchCount;
  int errcode;
  String errmsg;
  String message;

  MessageModel(
      {this.search,
        this.data,
        this.searchCount,
        this.errcode,
        this.errmsg,
        this.message});

  MessageModel.fromJson(Map<String, dynamic> json) {
    search = json['search'];
    if (json['data'] != null) {
      data = new List<Data>();
      json['data'].forEach((v) {
        data.add(new Data.fromJson(v));
      });
    }
    searchCount = json['search_count'];
    errcode = json['errcode'];
    errmsg = json['errmsg'];
    message = json['message'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['search'] = this.search;
    if (this.data != null) {
      data['data'] = this.data.map((v) => v.toJson()).toList();
    }
    data['search_count'] = this.searchCount;
    data['errcode'] = this.errcode;
    data['errmsg'] = this.errmsg;
    data['message'] = this.message;
    return data;
  }
}

class Data {
  int id;
  String sendingTime;
  String name;
  String message;
  int sendUserId;
  String sendUserName;
  List<int> receiveUserIds;
  List<ReceiveUserId> receiveUserId;

  Data(
      {this.id,
        this.sendingTime,
        this.name,
        this.message,
        this.sendUserId,
        this.sendUserName,
        this.receiveUserIds,
        this.receiveUserId});

  Data.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    sendingTime = json['sending_time'];
    name = json['name'];
    message = json['message'];
    sendUserId = json['send_user_id'];
    sendUserName = json['send_user_name'];
    receiveUserIds = json['receive_user_ids'].cast<int>();
    if (json['receive_user_id'] != null) {
      receiveUserId = new List<ReceiveUserId>();
      json['receive_user_id'].forEach((v) {
        receiveUserId.add(new ReceiveUserId.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['sending_time'] = this.sendingTime;
    data['name'] = this.name;
    data['message'] = this.message;
    data['send_user_id'] = this.sendUserId;
    data['send_user_name'] = this.sendUserName;
    data['receive_user_ids'] = this.receiveUserIds;
    if (this.receiveUserId != null) {
      data['receive_user_id'] =
          this.receiveUserId.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class ReceiveUserId {
  int id;
  String name;

  ReceiveUserId({this.id, this.name});

  ReceiveUserId.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['name'] = this.name;
    return data;
  }
}


